﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

using GeoWeb.Common;

namespace GeoWeb.Demo.UploadFileWebService
{
    /// <summary>
    /// UploadService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class UploadService : System.Web.Services.WebService
    {

        //当前用户名
        protected static string UserName = "keily";
        //当前队列
        internal static List<UploadLog> UploadLogList;


        public UploadService() {
            //检查存储路径
            string TempPath = Server.MapPath("TempFile/");
            string SavePath = Server.MapPath("StoreFile/");
            if (!IOHelper.IsExistDirectory(TempPath))
                IOHelper.CreateDir(TempPath);
            if (!IOHelper.IsExistDirectory(SavePath))
                IOHelper.CreateDir(SavePath);
            
        }
        
        /// <summary>
        /// 追加上传日志
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="fileSize"></param>
        /// <param name="appendSize"></param>
        /// <param name="fileSavePath"></param>
        /// <param name="userName"></param>
        /// <param name="opTime"></param>
        internal void AppendLog(string fileName, uint fileSize, int appendSize, string fileSavePath, string userName, DateTime opTime)
        {
            //check UploadLogList is null
            if (UploadLogList == null)
            {
                UploadLogList = new List<UploadLog>();
            }

            //get task list
            UploadLog curUploadLog = UploadLogList.Find(delegate(UploadLog u) { return u.FileName == fileName && u.FileSize == fileSize; });

            if (curUploadLog == null)
            {
                curUploadLog = new UploadLog(fileName, fileSize, appendSize, fileSavePath, userName, opTime);
                UploadLogList.Add(curUploadLog);
            }

            //write log
            curUploadLog.CurrentSize = curUploadLog.CurrentSize + appendSize;
            curUploadLog.OPTime = DateTime.Now;

            if (curUploadLog.Status == 1)
            {
                UploadLogList.Remove(curUploadLog);
            }
        }
        /// <summary>
        /// 读取日志
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        internal string ReadLog(string userName)
        {
            if (UploadLogList == null)
            {
                return "";
            }

            string FileName = "";
            string TempPath = Server.MapPath("TempFile/") + FileName + ".temp";

            List<UploadLog> curUploadLog = UploadLogList.FindAll(delegate(UploadLog u) { return u.UserName == userName; });
            if (curUploadLog != null)
            {
                string restr = "";
                foreach (UploadLog log in curUploadLog)
                {
                    //temp file
                    TempPath = Server.MapPath("TempFile/") + log.FileName + ".temp";

                    //check
                    if (!IOHelper.IsExistFile(TempPath))
                    {
                        log.Status = 1;
                    }
                    else
                    {
                        log.CurrentSize = (int)(new System.IO.FileInfo(TempPath)).Length;
                    }
                }

                //remove over
                curUploadLog.RemoveAll(delegate(UploadLog u) { return u.Status == 1; });

                //update status
                foreach (UploadLog elog in curUploadLog)
                {
                    if(elog.Status == 0)
                        restr += elog.FileName + "," + elog.FileSize + "," + elog.CurrentSize + ";";
                }

                return restr;
            }

            return "";
        }

        [WebMethod]
        public string ReadHistoryUpload(string userName)
        {
            //UserName is contant
            return ReadLog(UserName);
        }

        [WebMethod]
        public string CheckFile(string FileName)
        {
            string TempPath = Server.MapPath("TempFile/") + FileName + ".temp";
            if ( !IOHelper.IsExistFile(TempPath))
                return "文件不存在,0";
            else
            {
                string FileSize = (new System.IO.FileInfo(TempPath)).Length.ToString();
                return "文件已存在," + FileSize;
            }
        }

        [WebMethod]
        public string CopyFile(string FileName)
        {
            string TempPath = Server.MapPath("TempFile/") + FileName + ".temp";
            string SavePath = Server.MapPath("StoreFile/") + FileName;


            //由于文件尚在追加写入，等待0.3秒
            //System.Threading.Thread.Sleep(300);
            

            //如果目标中存在同名文件,则删除   
            if (IOHelper.IsExistFile(SavePath))
            {
                IOHelper.DeleteFile(SavePath);
            }
            
            //将文件复制到指定目录   
            IOHelper.CopyFile(TempPath, SavePath);

            //删除原始临时文件
            IOHelper.DeleteFile(TempPath);

            string Path = SavePath;
            return Path;
        }

        [WebMethod]
        public string DeleteFile(string FileName)
        {
            string TempPath = Server.MapPath("TempFile/") + FileName + ".temp";
            string SavePath = Server.MapPath("StoreFile/") + FileName;
            bool IsSuccess = false;

            //如果目标中存在同名文件,则删除   
            if (IOHelper.IsExistFile(TempPath))
            {
                IsSuccess = IOHelper.DeleteFile(TempPath);
            }
            if (IOHelper.IsExistFile(SavePath))
            {
                IsSuccess = IOHelper.DeleteFile(SavePath);
            }

            //remove over
            if (UploadLogList!=null)
                UploadLogList.RemoveAll(delegate(UploadLog u) { return u.FileName == FileName.Trim(); });

            return IsSuccess ? "success":"fault";
        }

        [WebMethod]
        public string WriteFile(string FileName,uint fileSize, byte[] filestrem)
        {

            string TempPath = Server.MapPath("TempFile/") + FileName + ".temp";
            if (!IOHelper.IsExistFile(TempPath))
            {
                System.IO.FileStream fs = new System.IO.FileStream(TempPath, System.IO.FileMode.Create);
                //获得字节数组
                byte[] data = filestrem;
                //开始写入
                fs.Write(data, 0, data.Length);
                //清空缓冲区、关闭流
                fs.Flush();
                fs.Close();

                //写日志
                AppendLog(FileName, fileSize, filestrem.Length, "", UserName,//UserName is contant
                    DateTime.Now);
            }
            else
            {
                System.Threading.Thread.Sleep(500);
                //追加文件
                using (System.IO.FileStream f = new System.IO.FileStream(TempPath, System.IO.FileMode.Append, System.IO.FileAccess.Write))
                {
                    byte[] bytes = filestrem;
                    f.Write(bytes, 0, bytes.Length);

                    //写日志
                    AppendLog(FileName, fileSize, filestrem.Length, "", UserName,//UserName is contant
                        DateTime.Now);
                }
            }

            return (new System.IO.FileInfo(TempPath)).Length.ToString();
        }
        

    }
}
